from sqlalchemy.orm import Session
from sqlalchemy import and_
from typing import List, Optional
import random

from ..models.question import Question, QuestionRecord
from ..schemas.question import QuestionCreate, QuestionUpdate

def get_questions_by_type(
    db: Session,
    subject: str,
    vehicle_type: str,
    exam_type: str,
    limit: int = 100
) -> List[Question]:
    """
    根据条件获取题目
    """
    query = db.query(Question).filter(
        and_(
            Question.subject == subject,
            Question.vehicle_type == vehicle_type,
            Question.exam_type == exam_type
        )
    )
    
    if exam_type == 'theory':
        # 随机获取指定数量的题目
        questions = query.all()
        if len(questions) > limit:
            questions = random.sample(questions, limit)
        return questions
    elif exam_type == 'special':
        # 获取专项训练题目
        return query.limit(limit).all()
    elif exam_type == 'sequence':
        # 顺序练习按ID排序
        return query.order_by(Question.id).all()
    
    return []

def get_question_by_id(db: Session, question_id: int) -> Optional[Question]:
    """
    根据ID获取题目
    """
    return db.query(Question).filter(Question.id == question_id).first()

def check_answer(db: Session, question_id: int, user_answer: str) -> dict:
    """
    检查答案是否正确
    """
    question = get_question_by_id(db, question_id)
    if not question:
        raise ValueError(f"题目不存在: {question_id}")
    
    is_correct = question.correct_answer == user_answer
    return {
        "correct": is_correct,
        "correct_answer": question.correct_answer,
        "explanation": question.explanation
    }

def save_question_record(
    db: Session,
    user_id: int,
    subject: str,
    score: float,
    answers: dict
) -> QuestionRecord:
    """
    保存答题记录
    """
    record = QuestionRecord(
        user_id=user_id,
        subject=subject,
        score=score,
        answers=answers
    )
    db.add(record)
    db.commit()
    db.refresh(record)
    return record

def get_wrong_questions(db: Session, user_id: int) -> List[Question]:
    """
    获取用户的错题列表
    """
    # 从答题记录中获取错误的题目ID
    records = db.query(QuestionRecord).filter(
        QuestionRecord.user_id == user_id
    ).all()
    
    wrong_question_ids = set()
    for record in records:
        for question_id, answer_info in record.answers.items():
            if not answer_info.get('correct', False):
                wrong_question_ids.add(int(question_id))
    
    # 获取错题详情
    if wrong_question_ids:
        return db.query(Question).filter(
            Question.id.in_(list(wrong_question_ids))
        ).all()
    
    return [] 